package cn.bs.controller;

import cn.bs.constant.Constants;
import cn.bs.domain.dao.*;
import cn.bs.domain.pojo.Result;
import cn.bs.domain.pojo.OrderPOJO;
import cn.bs.domain.vo.CanteenVO;
import cn.bs.domain.vo.MangerUserVO;
import cn.bs.domain.vo.OrderVO;
import cn.bs.domain.vo.UserVO;
import cn.bs.mapper.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/manage")
public class ManageController {

    @Autowired
    private OrderMapper orderMapper;;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DishesMapper dishesMapper;

    @Autowired
    private CanteenMapper canteenMapper;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Autowired
    private SeatMapper seatMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //查询订单数据
    @GetMapping("/getOrder")
    public Result getOrder(HttpServletRequest request,
                           @RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "10") int size) {
        System.out.println("获取订单列表");
        System.out.println("page:" + page + " size:" + size);

        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        System.out.println("用户权限 :" + userMapper.getById(userId).getType());

        if (userMapper.getById(userId).getType() != 0) {
            return Result.fail("权限不足");
        }

        int offset = (page - 1) * size;
        List<Orders> orders = orderMapper.getAllWithPagination(offset, size);

        List<OrderPOJO> orderPOJOList = orders.stream().map(order -> {
            OrderPOJO orderPOJO = new OrderPOJO();
            orderPOJO.setId(order.getId());
            orderPOJO.setUserName(userMapper.getById(order.getUserId()).getName());
            orderPOJO.setCanteenName(canteenMapper.getById(order.getCanteenId()).getName());
            orderPOJO.setSeatId(order.getSeatId());
            orderPOJO.setOrderAmount(order.getOrderAmount());
            orderPOJO.setOrderDate(order.getOrderDate());
            orderPOJO.setPayAmount(order.getPayAmount());
            orderPOJO.setPayDate(order.getPayDate());
            Integer status = order.getStatus();
            orderPOJO.setStatus(status == 0 ? "未支付" :
                    (status == 1 ? "已支付" :
                            (status == 2 ? "已取消" : "未知状态")));
            return orderPOJO;
        }).toList();

        OrderVO orderVO = new OrderVO();
        orderVO.setOrders(orderPOJOList);
        orderVO.setTotal(orderPOJOList.size());

        return Result.ok(orderVO);
    }


    //修改订单状态
    @PostMapping("/updateOrder")
    public Result updateOrder(HttpServletRequest request,@RequestParam Integer orderId,@RequestParam Integer status){
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }
        Orders orders = orderMapper.getById(orderId);

        if (orders == null){
            return Result.fail("订单不存在");
        }

        orders.setStatus(status);
        orderMapper.updateById(orders);
        return Result.ok("修改成功");
    }

    //删除订单，直接写到用户删除订单那里，到时候判断一下用户权限就行，已做
    @DeleteMapping("/deleteOrder")
    public Result deleteOrder(HttpServletRequest request,@RequestParam Integer orderId){
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }
        if (orderMapper.getById(orderId) == null){
            return Result.fail("订单不存在");
        }
        orderMapper.deleteById(orderId);
        return Result.ok("删除成功");
    }

    //修改菜品信息（图片，菜品类型）
    @PostMapping("/updateDishes")
    public Result updateDishes(
            @RequestParam("id") Integer id,
            @RequestParam("name") String name,
            @RequestParam("price") Double price,
            @RequestParam("description") String description,
            @RequestParam("type") Integer type,
            @RequestParam(value = "image", required = false) MultipartFile image
            ) throws IOException {

        Dishes dishes = dishesMapper.getById(id);
        dishes.setName(name);
        dishes.setPrice(price);
        dishes.setDescription(description);
        dishes.setTypeId(type);

        // 处理文件上传
        String imagePath = null;
        if (image != null && !image.isEmpty()) {
            try {
                String uploadDir = Constants.DOWNLOAD_PATH; // 文件保存路径
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs(); // 创建目录
                }

                // 生成唯一文件名
                String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                String filePath = Paths.get(uploadDir, fileName).toString();

                // 保存文件
                image.transferTo(new File(filePath));
                imagePath = fileName; // 保存相对路径
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("文件上传失败");
            }
            dishes.setImage(imagePath);
        }
        dishesMapper.updateById(dishes);

        return Result.ok("修改成功");
    }

    //获取菜品类型
    @GetMapping("/getType")
    public Result getType(){
        List<Type> types = typeMapper.getAll();
        return Result.ok(types);
    }

    //删除菜品
    @DeleteMapping("/deleteDishes")
    public Result deleteDishes(@RequestParam Integer dishId, HttpServletRequest request){

        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }

        if (dishesMapper.getById(dishId) == null){
            return Result.fail("菜品不存在");
        }

        dishesMapper.deleteById(dishId);

        return Result.ok("成功删除一个菜品");
    }

    //新增菜品信息
    @PostMapping("/addDishes")
    public Result addDishes(
            @RequestParam("canteenId") Integer canteenId,
            @RequestParam("name") String name,
            @RequestParam("price") Double price,
            @RequestParam("description") String description,
            @RequestParam("type") Integer type,
            @RequestParam("image") MultipartFile image,
            HttpServletRequest request
            ) throws IOException {

        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        if (image.isEmpty()) {
            return Result.fail("请选择图片");
        }

        Dishes dishes = new Dishes();
        dishes.setId(dishesMapper.getMaxId() + 1);
        dishes.setCanteenId(canteenId);
        dishes.setName(name);
        dishes.setPrice(price);
        dishes.setDescription(description);
        dishes.setTypeId(type);
        // 处理文件上传
        String imagePath = null;
        if (!image.isEmpty()) {
            try {
                String uploadDir = Constants.DOWNLOAD_PATH; // 文件保存路径
                File dir = new File(uploadDir);
                if (!dir.exists()) {
                    dir.mkdirs(); // 创建目录
                }

                // 生成唯一文件名
                String fileName = System.currentTimeMillis() + "_" + image.getOriginalFilename();
                String filePath = Paths.get(uploadDir, fileName).toString();

                // 保存文件
                image.transferTo(new File(filePath));
                imagePath = fileName; // 保存相对路径
            } catch (Exception e) {
                e.printStackTrace();
                return Result.fail("文件上传失败");
            }
        }
        dishes.setImage(imagePath);
        dishesMapper.insert(dishes);
        return Result.ok("成功添加一个菜品");
    }



    //修改餐厅信息（包括座位数量，座位容量）
    //修改座位容量，
    @PostMapping("/updateSeat")
    public Result updateSeat(
            @RequestParam("seatId") Integer seatId,
            @RequestParam("capacity") Integer capacity,
            @RequestParam("price") Double price,
            @RequestParam("number") Integer number,
            @RequestParam("status") Integer status,
            HttpServletRequest request
    ){
        System.out.println("修改座位");
        System.out.println("seatId" + seatId);
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        Seat seat = seatMapper.getById(seatId);
        if(seat == null){
            return Result.fail("该座位不存在");
        }

        Seat byNum = seatMapper.getByNum(number, seat.getCanteenId());
        if (byNum != null && !Objects.equals(byNum.getId(), seatId)){
            return Result.fail("该座位号已经存在");
        }

        seat.setCapacity(capacity);
        seat.setPrice(price);
//        if (seatMapper.getByNum(number, seat.getCanteenId()) != null){
//            return Result.fail("该座位号已经存在");
//        }
        seat.setNumber(number);
        seat.setStatus(status);

        seatMapper.updateById(seat);

        return Result.ok("修改成功");
    }

    //增加座位
    @PostMapping("/addSeat")
    public Result addSeat(
            @RequestParam("canteenId") Integer canteenId,
            @RequestParam("seatNum") Integer seatNum,
            @RequestParam("capacity") Integer capacity,
            @RequestParam("price") Double price,
            HttpServletRequest request
    ){
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        if (seatMapper.getByNum(seatNum, canteenId) != null){
            return Result.fail("该座位号已经存在");
        }
        if (canteenMapper.getById(canteenId) == null){
            return Result.fail("餐厅不存在");
        }
        Seat seat = new Seat();
        seat.setId(seatMapper.getMaxId() + 1);
        seat.setCanteenId(canteenId);
        seat.setNumber(seatNum);
        seat.setCapacity(capacity);
        seat.setPrice(price);
        seatMapper.insert(seat);
        return Result.ok("成功增加一个座位");
    }


    //删除座位
    @DeleteMapping("/deleteSeat")
    public Result deleteSeat(
            @RequestParam("seatId") Integer seatId,
            HttpServletRequest request
    ){
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        if (seatMapper.getById(seatId) == null){
            return Result.fail("座位不存在");
        }
        seatMapper.deleteById(seatId);
        return Result.ok("成功删除一个座位");
    }

    //删除用户发布的餐厅评价
    @DeleteMapping("/deleteReview")
    public Result deleteReview(
            @RequestParam("reviewId") Integer reviewId,
            HttpServletRequest request
    ){
        User user = userMapper
                .getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization"))));
        if (!Objects.equals(user.getId(), reviewMapper.getById(reviewId).getUserId()) && user.getType() != 0){
            return Result.fail("权限不足");
        }
        if (reviewMapper.getById(reviewId) == null){
            return Result.fail("餐厅评价不存在");
        }
        reviewMapper.deleteById(reviewId);
        return Result.ok("成功删除一个餐厅评价");
    }

    //删除用户发布的美食动态
    @DeleteMapping("/deletePost")
    public Result deletePost(
            @RequestParam("postId") Integer postId,
            HttpServletRequest request
    ){
        Post post = postMapper.getById(postId);
        String id = stringRedisTemplate.opsForValue().get(request.getHeader("Authorization"));
        User user = userMapper.getById(Integer.valueOf(id));
        if (!Objects.equals(user.getId(), post.getUserId())){
            if (user.getType() != 0){
                return Result.fail("权限不足");
            }else if (post == null){
                return Result.fail("美食动态不存在");
            }
        }
        postMapper.deleteById(postId);

        //删除该动态下的所有评论
        commentMapper.deleteByPostId(postId);

        return Result.ok("成功删除一个美食动态");
    }

    //删除用户发布的评论,评论的回复
    @DeleteMapping("/deleteComment")
    public Result deleteComment(
            @RequestParam("commentId") Integer commentId,
            HttpServletRequest request
    ){
        System.out.println("删除评论 :" + commentId);
        User user = userMapper
                .getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization"))));
        if (!Objects.equals(user.getId(), commentMapper.getById(commentId).getUserId()) &&user.getType() != 0
        && !Objects.equals(user.getId(), postMapper.getById(commentMapper.getById(commentId).getPostId()).getUserId())){
            return Result.fail("权限不足");
        }
        Comment comment = commentMapper.getById(commentId);
        if (comment == null){
            return Result.fail("评论不存在");
        }else if(comment.getStatus() == 1){
            return Result.fail("评论已被删除");
        }
        comment.setStatus(1);
        commentMapper.updateById(comment);
        return Result.ok("成功删除一个评论");
    }

    //查询用户数据, 除了管理员和本人都不行
    @GetMapping("/getUser")
    public Result getUser(HttpServletRequest request){
        System.out.println("管理员getUser");
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }

        List<User> users = userMapper.getAll();
        List<UserVO> userVOList = users.stream().map(user -> {
            UserVO userVO = new UserVO();
            userVO.setId(user.getId());
            userVO.setName(user.getName());
//            userVO.setPwd(user.getPwd());
            userVO.setTelephone(user.getTelephone());
            userVO.setType(user.getType() == 1 ? "普通用户" : "管理员");
            userVO.setDate(user.getDate());
            return userVO;
        }).toList();

        MangerUserVO mangerUserVO = new MangerUserVO();
        mangerUserVO.setUsers(userVOList);
        mangerUserVO.setTotal(users.size());

        return Result.ok(mangerUserVO);
    }

    //根据用户名模糊查询用户列表
    @GetMapping("/getUserByName")
    public Result getUserByName(@RequestParam String name, HttpServletRequest request){
        System.out.println("管理员getUser");
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }
        List<User> users = userMapper.getByName(name);
        List<UserVO> userVOList = users.stream().map(user -> {
            UserVO userVO = new UserVO();
            userVO.setId(user.getId());
            userVO.setName(user.getName());
            userVO.setTelephone(user.getTelephone());
            userVO.setType(user.getType() == 1 ? "普通用户" : "管理员");
            userVO.setDate(user.getDate());
            return userVO;
        }).toList();

        MangerUserVO mangerUserVO = new MangerUserVO();
        mangerUserVO.setUsers(userVOList);
        mangerUserVO.setTotal(users.size());
        return Result.ok(mangerUserVO);
    }


    //修改用户数据（修改用户权限）
    @PostMapping("/updateUser")
    public Result updateUser(HttpServletRequest request,
                             @RequestParam Integer userId,
                             @RequestParam Integer type){
        System.out.println("管理员updateUser" + userId + " " + type);
        String token = request.getHeader("Authorization");
        Integer managerId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (Objects.equals(userId, managerId)){
            return Result.fail("不能修改自己");
        }
        if (userMapper.getById(managerId).getType() != 0){
            return Result.fail("权限不足");
        }
        if (userMapper.getById(userId) == null){
            return Result.fail("用户不存在");
        }

        User user = userMapper.getById(userId);
        user.setType(type);
        userMapper.updateById(user);
        return Result.ok("修改成功");
    }

    //删除用户
    @DeleteMapping("/deleteUser")
    public Result deleteUser(HttpServletRequest request, Integer userId){
        System.out.println("管理员deleteUser" + userId);
        String token = request.getHeader("Authorization");
        Integer managerId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (Objects.equals(userId, managerId)){
            return Result.fail("不能删除自己");
        }
        if (userMapper.getById(managerId).getType() != 0){
            return Result.fail("权限不足");
        }
        if (userMapper.getById(userId) == null){
            return Result.fail("用户不存在");
        }
        userMapper.deleteById(userId);
        orderMapper.deleteByUserId(userId);
        reviewMapper.deleteByUserId(userId);
        postMapper.deleteByUserId(userId);
        commentMapper.deleteByUserId(userId);
        return Result.ok("删除成功");
    }

    //查询餐厅列表
    @GetMapping("/getCanteen")
    public Result getCanteen(HttpServletRequest request){
        System.out.println("管理员getCanteen");
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }
        List<Canteen> canteens = canteenMapper.getAll();
        CanteenVO canteenVO = new CanteenVO();
        canteenVO.setCanteens(canteens);
        canteenVO.setTotal(canteenMapper.getTotalCanteens());
        return Result.ok(canteenVO);
    }

    //根据餐厅名模糊查询店铺列表
    @GetMapping("/getCanteenByName")
    public Result getCanteenByName(@RequestParam String name, HttpServletRequest request){
        System.out.println("管理员getCanteenByName");
        String token = request.getHeader("Authorization");
        Integer userId = Integer.valueOf(stringRedisTemplate.opsForValue().get(token));
        if (userMapper.getById(userId).getType() != 0){
            return Result.fail("权限不足");
        }
        List<Canteen> canteens = canteenMapper.getCanteenByName(name);
        CanteenVO canteenVO = new CanteenVO();
        canteenVO.setCanteens(canteens);
        canteenVO.setTotal(canteens.size());
        return Result.ok(canteenVO);
    }

    //修改餐厅信息
    @PostMapping("/updateCanteen")
    public Result updateCanteen(
            @RequestParam("id") Integer id,
            @RequestParam("name") String name,
            @RequestParam("position") String position,
            HttpServletRequest request
    ){
        System.out.println("管理员updateCanteen");
        System.out.println("Received id: " + id);
        System.out.println("Received name: " + name);
        System.out.println("Received position: " + position);
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        Canteen canteen = canteenMapper.getById(id);
        if (canteen == null){
            return Result.fail("餐厅不存在");
        }
        canteen.setName(name);
        canteen.setPosition(position);
        canteenMapper.updateById(canteen);
        return Result.ok("成功修改餐厅信息");
    }
    //新增餐厅
    @PostMapping("/addCanteen")
    public Result addCanteen(
            @RequestParam("name") String name,
            @RequestParam("position") String position,
            HttpServletRequest request
    ){
        System.out.println("管理员addCanteen");
        System.out.println("Received name: " + name);
        System.out.println("Received position: " + position);
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }

        Canteen canteen = new Canteen();

//        canteen.setId(canteenMapper.getMaxId() + 2);
        canteen.setName(name);
        canteen.setPosition(position);

        canteenMapper.insert(canteen);

        return Result.ok("成功添加一个餐厅");
    }

    //删除餐厅
    @DeleteMapping("/deleteCanteen")
    public Result deleteCanteen(
            @RequestParam("canteenId") Integer canteenId,
            HttpServletRequest request
    ){
        System.out.println("管理员deleteCanteen");
        System.out.println("Received canteenId: " + canteenId);
        if (userMapper.getById(Integer.valueOf(stringRedisTemplate.opsForValue().get(request.getHeader("Authorization")))).getType() != 0){
            return Result.fail("权限不足");
        }
        if (canteenMapper.getById(canteenId) == null){
            return Result.fail("餐厅不存在");
        }
        canteenMapper.deleteById(canteenId);

        seatMapper.deleteByCanteenId(canteenId);

        dishesMapper.deleteByCanteenId(canteenId);

        reviewMapper.deleteByCanteenId(canteenId);

        return Result.ok("成功删除一个餐厅");
    }

}
